package org.leiyang.netty.controller;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.leiyang.common.dtos.MsgDTO;
import org.leiyang.common.dtos.OffLineMsgsVO;
import org.leiyang.common.dtos.R;
import org.leiyang.common.holder.MsgServerAndClientHolder;
import org.leiyang.common.holder.OnlineServerHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * 本地发送消息到MsgServer
 */
@RestController
@RequestMapping("/local")
public class LocalSendController {
    private final static Logger logger = LoggerFactory.getLogger(LocalSendController.class);
    private final OnlineServerHolder onlineServerHolder;
    private final MsgServerAndClientHolder msgServerAndClientHolder;

    public LocalSendController(OnlineServerHolder onlineServerHolder, MsgServerAndClientHolder msgServerAndClientHolder) {
        this.onlineServerHolder = onlineServerHolder;
        this.msgServerAndClientHolder = msgServerAndClientHolder;
    }

    /**
     * 将接收到的消息批量发送给本地的MsgServer
     * 使用场景: 用户登录成功之后，将离线期间收到的消息发送给客户端
     * @return 发送是否成功
     */
    @PostMapping("/batch/send")
    public Boolean batchLocalMsgsSend(@RequestBody OffLineMsgsVO offLineMsgsVO) {
        String msgType = offLineMsgsVO.getOnlineMsg() ? "在线" : "离线";
        List<MsgDTO> msgs = offLineMsgsVO.getMsgs();
        logger.info("已收到{}条{}消息，待发送.", msgs.size(), msgType);
        if(msgs.isEmpty()) {
            return true;
        }
        Channel channel = onlineServerHolder.gotCachedChannel(offLineMsgsVO.getChannelId());
        if(Objects.isNull(channel)) {
            logger.error("[batchLocalMsgsSend]未获取到对应的Channel信息.当前本地缓存的channelIds: {}", onlineServerHolder.cachedChannelIds());
            return false;
        }

        //对msgs按照fromUserId进行分组
//        Map<Long, List<Message>> msgsGroupBy = msgs.stream().collect(Collectors.groupingBy(Message::getFromUserId));
        R<List<MsgDTO>> reps = R.ok(msgs, offLineMsgsVO.getOnlineMsg() ? "online msgs" : "history msgs");
        //这里发送文本格式消息
        final String repsStr = JSON.toJSONString(reps);
        WebSocketFrame content = new TextWebSocketFrame(repsStr);
        channel.writeAndFlush(content).addListener(future -> {
            if (future.isSuccess()) {
                logger.info("Msg Server端已批量发送{}消息到客户端: {}", msgType, repsStr);
                return;
            }
            logger.error("Msg Server端批量发送{}消息到客户端是否成功: {}, 异常信息: ", msgType, future.isSuccess(), future.cause());
        });
        return true;
    }

    /**
     * RSocket版本的{@link LocalSendController#batchLocalMsgsSend(OffLineMsgsVO)}
     */
    @MessageMapping("localsend")
    public Mono<Boolean> batchLocalMsgsSend_V1(OffLineMsgsVO offLineMsgsVO) {
        return Mono.just(batchLocalMsgsSend(offLineMsgsVO));
    }

    /**
     * 移除netty客户端的记录
     * 一般使用在客户端下线的场景下
     */
    @PostMapping("/remove/client")
    public Mono<Boolean> removeOfflineClient(@RequestBody String clientId) {
        return msgServerAndClientHolder.removeOfflineClient(clientId);
    }
}
